package com.sea.base.ui

import com.sea.base.ext.global.isMainThread
import com.sea.base.ext.view.doOnDestroyed
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import java.io.Serializable

private object UNINITIALIZED_VALUE

/**
 * 跟着ui的生命周期走，当destroy时会销毁，当再次create时会创建新的
 */
class UILazyDelegate<out T>(
    private val ui: IUIContext,
    private val initializer: () -> T
) : Lazy<T>, Serializable {
    private var _value: Any? = UNINITIALIZED_VALUE

    override val value: T
        get() {
            if (!isInitialized()) {
                if (isMainThread()) createForMain() else runBlocking(Dispatchers.Main) { createForMain() }
                if (!isInitialized()) {
                    throw IllegalStateException("不允许在super.onDestroy后调用")
                }
            }
            return _value as T
        }

    private fun createForMain() {
        _value = initializer.invoke()
        ui.doOnDestroyed {
            _value = UNINITIALIZED_VALUE
        }
    }

    override fun isInitialized(): Boolean = _value !== UNINITIALIZED_VALUE

    override fun toString(): String =
        if (isInitialized()) value.toString() else "Lazy value not initialized yet."
}